<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="模板编码" prop="templateCode">
        <el-input
          v-model="queryParams.templateCode"
          placeholder="请输入模板编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="适用职业" prop="applicableProfession">
        <el-input
          v-model="queryParams.applicableProfession"
          placeholder="请输入适用职业"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="评价方式" prop="applicableMethod">
        <el-select
          v-model="queryParams.applicableMethod"
          placeholder="请选择评价方式"
          clearable
          class="!w-240px"
        >
          <el-option label="认定评价" value="assessment" />
          <el-option label="考试评价" value="examination" />
          <el-option label="混合评价" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="模板状态" prop="templateStatus">
        <el-select
          v-model="queryParams.templateStatus"
          placeholder="请选择模板状态"
          clearable
          class="!w-240px"
        >
          <el-option label="草稿" :value="0" />
          <el-option label="已发布" :value="1" />
          <el-option label="已停用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefault">
        <el-select
          v-model="queryParams.isDefault"
          placeholder="请选择是否默认"
          clearable
          class="!w-240px"
        >
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:template:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:template:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 模板卡片列表 -->
  <ContentWrap>
    <div v-loading="loading" class="template-grid">
      <div
        v-for="template in list"
        :key="template.id"
        class="template-card"
        @click="openTemplateDetail(template)"
      >
        <!-- 卡片头部 -->
        <div class="card-header">
          <div class="template-icon">
            <Icon icon="ep:document" size="24" />
          </div>
          <div class="template-status">
            <el-tag :type="getTemplateStatusTagType(template.templateStatus)" size="small">
              {{ getTemplateStatusText(template.templateStatus) }}
            </el-tag>
          </div>
        </div>

        <!-- 卡片内容 -->
        <div class="card-content">
          <h3 class="template-name" :title="template.templateName">
            {{ template.templateName }}
          </h3>
          <div class="template-info">
            <div class="info-item">
              <span class="label">职业：</span>
              <span class="value">{{ template.applicableProfession || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">等级：</span>
              <span class="value">{{ template.applicableLevel || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">方式：</span>
              <dict-tag :type="DICT_TYPE.EVAL_EVALUATION_METHOD" :value="template.applicableMethod" />
            </div>
            <div class="info-item">
              <span class="label">分数：</span>
              <span class="value">{{ template.passScore }}/{{ template.totalScore }}</span>
            </div>
          </div>
        </div>

        <!-- 卡片底部 -->
        <div class="card-footer">
          <div class="template-meta">
            <span class="version">v{{ template.templateVersion || '1.0' }}</span>
            <span class="usage">使用{{ template.usageCount || 0 }}次</span>
            <el-tag v-if="template.isDefault" type="success" size="small">默认</el-tag>
          </div>
          <div class="card-actions" @click.stop>
            <el-button
              link
              type="primary"
              size="small"
              @click="openForm('update', template.id)"
              v-hasPermi="['eval:template:update']"
              v-if="template.templateStatus === 0"
            >
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, template)">
              <el-button link type="primary" size="small">
                更多<Icon icon="ep:arrow-down" class="ml-5px" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="publish" v-if="template.templateStatus === 0">
                    发布
                  </el-dropdown-item>
                  <el-dropdown-item command="disable" v-if="template.templateStatus === 1">
                    停用
                  </el-dropdown-item>
                  <el-dropdown-item command="copy">
                    复制
                  </el-dropdown-item>
                  <el-dropdown-item command="setDefault" v-if="!template.isDefault && template.templateStatus === 1">
                    设为默认
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" v-if="template.templateStatus === 0">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && list.length === 0" class="empty-state">
        <el-empty description="暂无评价模板" />
      </div>
    </div>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TemplateForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <TemplateDetail ref="detailRef" />

  <!-- 模板预览弹窗 -->
  <TemplatePreview ref="previewRef" />

  <!-- 复制弹窗 -->
  <TemplateCopy ref="copyRef" @success="getList" />

  <!-- 设为默认弹窗 -->
  <TemplateSetDefault ref="setDefaultRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalTemplateVO, 
  EvalTemplatePageReqVO, 
  getTemplatePage, 
  deleteTemplate, 
  exportTemplate,
  publishTemplate,
  disableTemplate
} from '@/api/eval/template'
import TemplateForm from './TemplateForm.vue'
import TemplateDetail from './TemplateDetail.vue'
import TemplatePreview from './TemplatePreview.vue'
import TemplateCopy from './TemplateCopy.vue'
import TemplateSetDefault from './TemplateSetDefault.vue'

/** 评价模板 列表 */
defineOptions({ name: 'EvalTemplate' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalTemplateVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalTemplatePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  templateCode: undefined,
  templateName: undefined,
  applicableProfession: undefined,
  applicableMethod: undefined,
  templateStatus: undefined,
  isDefault: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getTemplatePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 点击模板卡片打开预览 */
const previewRef = ref()
const openTemplateDetail = (template: EvalTemplateVO) => {
  previewRef.value.open(template.id!)
}

/** 复制操作 */
const copyRef = ref()
const openCopy = (id: number) => {
  copyRef.value.open(id)
}

/** 设为默认操作 */
const setDefaultRef = ref()
const openSetDefault = (id: number) => {
  setDefaultRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalTemplateVO) => {
  switch (command) {
    case 'publish':
      await handlePublish(row.id!)
      break
    case 'disable':
      await handleDisable(row.id!)
      break
    case 'copy':
      openCopy(row.id!)
      break
    case 'setDefault':
      openSetDefault(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 发布模板 */
const handlePublish = async (id: number) => {
  try {
    await message.confirm('确认发布该模板？发布后将无法修改。')
    await publishTemplate(id)
    message.success('发布成功')
    await getList()
  } catch {}
}

/** 停用模板 */
const handleDisable = async (id: number) => {
  try {
    await message.confirm('确认停用该模板？停用后将无法使用。')
    await disableTemplate(id)
    message.success('停用成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteTemplate(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportTemplate(queryParams)
    download.excel(data, '评价模板.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取模板状态标签类型 */
const getTemplateStatusTagType = (status: number) => {
  const typeMap = { 0: 'warning', 1: 'success', 2: 'danger' }
  return typeMap[status] || ''
}

/** 获取模板状态文本 */
const getTemplateStatusText = (status: number) => {
  const textMap = { 0: '草稿', 1: '已发布', 2: '已停用' }
  return textMap[status] || '未知'
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped>
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.template-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fff;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.template-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.template-icon {
  color: #409eff;
}

.card-content {
  margin-bottom: 16px;
}

.template-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.template-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.info-item .label {
  color: #909399;
  min-width: 40px;
  margin-right: 8px;
}

.info-item .value {
  color: #606266;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.template-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.card-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px 0;
  }

  .template-card {
    padding: 12px;
  }
}
</style>
